package com.example.myapplication.handler;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.Nullable;

import java.util.Random;

/**
 * Created by ymz0427 on 2021/10/16
 */
public class RequestIntentService extends IntentService {

    private static final String TAG = "RequestIntentService";

    private int count = 0;
    private boolean isFinished = false;

    public RequestIntentService() {
        this("请求");
    }

    public RequestIntentService(String name) {
        super(name);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        count++;
        if (!isFinished) {
            int result = request();
            Log.d(TAG, String.format("第%s次登录， 登录结果result = %s", count, result));
            if (result % 2 == 0) {
                Log.d(TAG, "登录结束");
                isFinished = true;
            }
        }
    }

    /**
     * 模拟请求
     */
    private int request() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Random().nextInt(1000);
    }
}
